//
//  YTWithDrawMoneyViewModel.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/5/27.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTWithDrawMoneyViewModel.h"
#import "YTUserProfileServices.h"
#import "YTWithdrawAccountModel.h"
#import <CocoaSecurity/CocoaSecurity.h>

@interface YTWithDrawMoneyViewModel ()

@property (copy, nonatomic, readwrite) NSString *moneyText;
@property (copy, nonatomic, readwrite) NSString *max;
@property (strong, nonatomic, readwrite) NSMutableArray<YTWithdrawAccountModel *> *accountList;
@property (strong, nonatomic, readwrite) RACSignal *loadAccountList;
@property (strong, nonatomic, readwrite) RACCommand *withdrawMoney;

@end

@implementation YTWithDrawMoneyViewModel

- (void)initialize {
    _accountList = [NSMutableArray array];
    
    RACSignal *enableSignal = [RACSignal combineLatest:@[RACObserve(self, moneyText), RACObserve(self, max)]
                                                reduce:^id (NSString *money, NSString *max){
        return @(money.length >= 1 && ([money floatValue] != 0) && [money floatValue] <= [max floatValue]);
    }];
    
    @weakify(self);
    _loadAccountList = [[YTUserProfileServices loadWithdrawAccount] map:^id(NSDictionary *response) {
        @strongify(self);
        NSDictionary *data = response[@"responseData"];
        self.accountList = [[NSArray yy_modelArrayWithClass:[YTWithdrawAccountModel class]
                                                       json:data[@"accountList"]] mutableCopy];
        return self.accountList;
    }];
    _withdrawMoney = [[RACCommand alloc] initWithEnabled:enableSignal signalBlock:^RACSignal *(NSString *password) {
        @strongify(self);
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"amount"] = self.moneyText;
        dict[@"accountId"] = self.account_id;
        NSString *userID = [YTUtilityManager manager].userModel.userId;
        NSString *passwrod = [NSString stringWithFormat:@"%@%@paypassword", password, userID];
        NSString *passwordMD5 = [CocoaSecurity md5:passwrod].hex;
        NSString *paySum = [NSString stringWithFormat:@"drawMoney%@%@%@%@yitu8.net", self.account_id, self.moneyText, userID, passwordMD5];
        dict[@"paySum"] = [CocoaSecurity md5:paySum].hex;
        return [YTUserProfileServices withdraw:dict];
    }];
}

@end
